import { useEffect, useMemo, useRef } from 'react';
import { noop } from '../fn';

/**
 *
 * @param {function} fn 定时执行函数, 会插入 cacheRef
 * @param {number} delay  定时器时间
 * @param {array} deps      依赖
 * @param {boolean} immediate  是否立即执行一次, 默认 false
 * @returns {[function, function]} [clear, run], clear清除定时器, run立即执行一次, 会插入cacheRef
 */
function useInterval(fn, delay, deps, immediate = false) {
  const timerRef = useRef();
  const cacheRef = useRef();

  const fnRef = useRef(noop);

  // 定义执行的函数
  useEffect(() => {
    fnRef.current = () => {
      fn(cacheRef, ...deps);
    };
  }, [cacheRef, fn, deps]);

  // 清除定时器
  const clear = useMemo(() => {
    return () => {
      clearInterval(timerRef.current);
      timerRef.current = undefined;
    };
  }, [timerRef]);

  // 定时执行
  useEffect(() => {
    clear();

    if (timerRef.current === null) {
      return;
    }

    if (immediate) {
      // 立即执行一次
      fnRef.current();
    }

    // 定时器启动
    timerRef.current = setInterval(() => {
      fnRef.current();
    }, delay);

    return clear;
  }, [timerRef, fnRef, clear, delay]);

  return [
    // clear
    () => {
      clear();
      timerRef.current = null;
    },
    // run
    fnRef,
  ];
}

export { useInterval };
